﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using digit.Core;

namespace SMS.CDR
{
    public partial class CDRMonitor : System.Windows.Forms.Form
    {
        // Fields
        private string CDRDirGPC;
        private IContainer components;
        private int mkFolder;
        private string DateCDR;
        private string PassFTPGPC;
        private int SeqNumVms;
        private int SeqNumGpc;
        private string ServerFTPGPC;
        private Timer timeWrite;
        private string UserFTPGPC;
        private TabPage tabGpc;
        private TextBox txtLogWriter;
        private GroupBox gbxGPC;
        private TextBox txtTimeGpc;
        private Label label5;
        private TextBox txtDirGpc;
        private Label label4;
        private TextBox txtPassGpc;
        private Label label3;
        private TextBox txtUserGpc;
        private Label label2;
        private TextBox txtServerGpc;
        private Label label1;
        private TabControl tabCDR;
        private TabPage tabFTP;
        private Button btnResendGpc;
        private CheckBox chkEnableTransfer;
        private TextBox txtLogFtp;
        private Button btnExit;
        private Button btnClear;        
        private Button btnStartGpc;

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.timeWrite = new System.Windows.Forms.Timer(this.components);
            this.tabGpc = new System.Windows.Forms.TabPage();
            this.btnExit = new System.Windows.Forms.Button();
            this.btnClear = new System.Windows.Forms.Button();
            this.txtLogWriter = new System.Windows.Forms.TextBox();
            this.gbxGPC = new System.Windows.Forms.GroupBox();
            this.txtTimeGpc = new System.Windows.Forms.TextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.txtDirGpc = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.txtPassGpc = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.txtUserGpc = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.txtServerGpc = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.btnStartGpc = new System.Windows.Forms.Button();
            this.tabCDR = new System.Windows.Forms.TabControl();
            this.tabFTP = new System.Windows.Forms.TabPage();
            this.btnResendGpc = new System.Windows.Forms.Button();
            this.chkEnableTransfer = new System.Windows.Forms.CheckBox();
            this.txtLogFtp = new System.Windows.Forms.TextBox();
            this.tabGpc.SuspendLayout();
            this.gbxGPC.SuspendLayout();
            this.tabCDR.SuspendLayout();
            this.tabFTP.SuspendLayout();
            this.SuspendLayout();
            // 
            // timeWrite
            // 
            this.timeWrite.Tick += new System.EventHandler(this.timeWrite_Tick);
            // 
            // tabGpc
            // 
            this.tabGpc.Controls.Add(this.btnExit);
            this.tabGpc.Controls.Add(this.btnClear);
            this.tabGpc.Controls.Add(this.txtLogWriter);
            this.tabGpc.Controls.Add(this.gbxGPC);
            this.tabGpc.Controls.Add(this.btnStartGpc);
            this.tabGpc.Location = new System.Drawing.Point(4, 22);
            this.tabGpc.Name = "tabGpc";
            this.tabGpc.Size = new System.Drawing.Size(616, 282);
            this.tabGpc.TabIndex = 0;
            this.tabGpc.Text = "CDR Writer";
            this.tabGpc.UseVisualStyleBackColor = true;
            // 
            // btnExit
            // 
            this.btnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnExit.Location = new System.Drawing.Point(497, 89);
            this.btnExit.Name = "btnExit";
            this.btnExit.Size = new System.Drawing.Size(102, 26);
            this.btnExit.TabIndex = 26;
            this.btnExit.Text = "&Exit";
            this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
            // 
            // btnClear
            // 
            this.btnClear.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnClear.Location = new System.Drawing.Point(497, 59);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(102, 26);
            this.btnClear.TabIndex = 25;
            this.btnClear.Text = "&Clear";
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // txtLogWriter
            // 
            this.txtLogWriter.Location = new System.Drawing.Point(11, 125);
            this.txtLogWriter.Multiline = true;
            this.txtLogWriter.Name = "txtLogWriter";
            this.txtLogWriter.ReadOnly = true;
            this.txtLogWriter.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtLogWriter.Size = new System.Drawing.Size(588, 145);
            this.txtLogWriter.TabIndex = 17;
            // 
            // gbxGPC
            // 
            this.gbxGPC.Controls.Add(this.txtTimeGpc);
            this.gbxGPC.Controls.Add(this.label5);
            this.gbxGPC.Controls.Add(this.txtDirGpc);
            this.gbxGPC.Controls.Add(this.label4);
            this.gbxGPC.Controls.Add(this.txtPassGpc);
            this.gbxGPC.Controls.Add(this.label3);
            this.gbxGPC.Controls.Add(this.txtUserGpc);
            this.gbxGPC.Controls.Add(this.label2);
            this.gbxGPC.Controls.Add(this.txtServerGpc);
            this.gbxGPC.Controls.Add(this.label1);
            this.gbxGPC.Location = new System.Drawing.Point(11, 10);
            this.gbxGPC.Name = "gbxGPC";
            this.gbxGPC.Size = new System.Drawing.Size(473, 105);
            this.gbxGPC.TabIndex = 15;
            this.gbxGPC.TabStop = false;
            this.gbxGPC.Text = "FTP Info";
            // 
            // txtTimeGpc
            // 
            this.txtTimeGpc.Location = new System.Drawing.Point(295, 17);
            this.txtTimeGpc.Name = "txtTimeGpc";
            this.txtTimeGpc.Size = new System.Drawing.Size(60, 20);
            this.txtTimeGpc.TabIndex = 18;
            this.txtTimeGpc.Text = "10";
            // 
            // label5
            // 
            this.label5.Location = new System.Drawing.Point(217, 21);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(73, 16);
            this.label5.TabIndex = 19;
            this.label5.Text = "Timer Interval";
            // 
            // txtDirGpc
            // 
            this.txtDirGpc.Location = new System.Drawing.Point(295, 48);
            this.txtDirGpc.Name = "txtDirGpc";
            this.txtDirGpc.Size = new System.Drawing.Size(162, 20);
            this.txtDirGpc.TabIndex = 16;
            this.txtDirGpc.Text = "D:\\vn1102\\Cdr\\CDRGPC\\";
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(217, 51);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(66, 16);
            this.label4.TabIndex = 17;
            this.label4.Text = "Client Store";
            // 
            // txtPassGpc
            // 
            this.txtPassGpc.Location = new System.Drawing.Point(93, 72);
            this.txtPassGpc.Name = "txtPassGpc";
            this.txtPassGpc.PasswordChar = '*';
            this.txtPassGpc.Size = new System.Drawing.Size(105, 20);
            this.txtPassGpc.TabIndex = 14;
            this.txtPassGpc.Text = "dec8x78";
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(20, 72);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(56, 16);
            this.label3.TabIndex = 15;
            this.label3.Text = "Password";
            // 
            // txtUserGpc
            // 
            this.txtUserGpc.Location = new System.Drawing.Point(93, 44);
            this.txtUserGpc.Name = "txtUserGpc";
            this.txtUserGpc.Size = new System.Drawing.Size(105, 20);
            this.txtUserGpc.TabIndex = 12;
            this.txtUserGpc.Text = "8x78";
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(19, 46);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(70, 16);
            this.label2.TabIndex = 13;
            this.label2.Text = "User Name";
            // 
            // txtServerGpc
            // 
            this.txtServerGpc.Location = new System.Drawing.Point(93, 16);
            this.txtServerGpc.Name = "txtServerGpc";
            this.txtServerGpc.Size = new System.Drawing.Size(105, 20);
            this.txtServerGpc.TabIndex = 10;
            this.txtServerGpc.Text = "203.162.20.93";
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(20, 20);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(56, 16);
            this.label1.TabIndex = 11;
            this.label1.Text = "Server";
            // 
            // btnStartGpc
            // 
            this.btnStartGpc.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnStartGpc.Location = new System.Drawing.Point(497, 15);
            this.btnStartGpc.Name = "btnStartGpc";
            this.btnStartGpc.Size = new System.Drawing.Size(102, 40);
            this.btnStartGpc.TabIndex = 14;
            this.btnStartGpc.Text = "Start";
            this.btnStartGpc.Click += new System.EventHandler(this.btnStartGpc_Click);
            // 
            // tabCDR
            // 
            this.tabCDR.Controls.Add(this.tabGpc);
            this.tabCDR.Controls.Add(this.tabFTP);
            this.tabCDR.Location = new System.Drawing.Point(8, 3);
            this.tabCDR.Name = "tabCDR";
            this.tabCDR.SelectedIndex = 0;
            this.tabCDR.Size = new System.Drawing.Size(624, 308);
            this.tabCDR.TabIndex = 0;
            // 
            // tabFTP
            // 
            this.tabFTP.Controls.Add(this.btnResendGpc);
            this.tabFTP.Controls.Add(this.chkEnableTransfer);
            this.tabFTP.Controls.Add(this.txtLogFtp);
            this.tabFTP.Location = new System.Drawing.Point(4, 22);
            this.tabFTP.Name = "tabFTP";
            this.tabFTP.Padding = new System.Windows.Forms.Padding(3);
            this.tabFTP.Size = new System.Drawing.Size(616, 282);
            this.tabFTP.TabIndex = 1;
            this.tabFTP.Text = "FTP Transfer";
            this.tabFTP.UseVisualStyleBackColor = true;
            // 
            // btnResendGpc
            // 
            this.btnResendGpc.Location = new System.Drawing.Point(501, 11);
            this.btnResendGpc.Name = "btnResendGpc";
            this.btnResendGpc.Size = new System.Drawing.Size(102, 31);
            this.btnResendGpc.TabIndex = 28;
            this.btnResendGpc.Text = "&Re-send";
            this.btnResendGpc.UseVisualStyleBackColor = true;
            this.btnResendGpc.Click += new System.EventHandler(this.btnResendGpc_Click);
            // 
            // chkEnableTransfer
            // 
            this.chkEnableTransfer.AutoSize = true;
            this.chkEnableTransfer.Checked = true;
            this.chkEnableTransfer.CheckState = System.Windows.Forms.CheckState.Checked;
            this.chkEnableTransfer.Location = new System.Drawing.Point(13, 23);
            this.chkEnableTransfer.Name = "chkEnableTransfer";
            this.chkEnableTransfer.Size = new System.Drawing.Size(59, 17);
            this.chkEnableTransfer.TabIndex = 27;
            this.chkEnableTransfer.Text = "&Enable";
            this.chkEnableTransfer.UseVisualStyleBackColor = true;
            // 
            // txtLogFtp
            // 
            this.txtLogFtp.Location = new System.Drawing.Point(13, 50);
            this.txtLogFtp.Multiline = true;
            this.txtLogFtp.Name = "txtLogFtp";
            this.txtLogFtp.ReadOnly = true;
            this.txtLogFtp.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtLogFtp.Size = new System.Drawing.Size(590, 222);
            this.txtLogFtp.TabIndex = 26;
            // 
            // CDRMonitor
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(644, 323);
            this.Controls.Add(this.tabCDR);
            this.MaximizeBox = false;
            this.Name = "CDRMonitor";
            this.Text = "GPC CDR Writer & Transfer";
            this.Load += new System.EventHandler(this.CDRMonitor_Load);
            this.tabGpc.ResumeLayout(false);
            this.tabGpc.PerformLayout();
            this.gbxGPC.ResumeLayout(false);
            this.gbxGPC.PerformLayout();
            this.tabCDR.ResumeLayout(false);
            this.tabFTP.ResumeLayout(false);
            this.tabFTP.PerformLayout();
            this.ResumeLayout(false);

        }
        #endregion

        // Methods
        public CDRMonitor()
        {
            this.InitializeComponent();
        }

        private void CDRMonitor_Load(object sender, EventArgs e)
        {
            this.Text = this.Text + " - " + Util.GetAppSettings("ServiceRange");
            this.DateCDR = Util.GetAppSettings("DateCDR");
            this.SeqNumGpc = Util.ToInteger(Util.GetAppSettings("SeqNumGpc"));
            this.SeqNumVms = Util.ToInteger(Util.GetAppSettings("SeqNumVms"));

            if (DateTime.Now.ToString("dd/MM/yyyy") != this.DateCDR)
            {
                ConfigSettings.WriteSetting("DateCDR", DateTime.Now.ToString("dd/MM/yyyy"));
                this.DateCDR = DateTime.Now.ToString("dd/MM/yyyy");
            }

            this.mkFolder = Util.ToInteger(Util.GetAppSettings("GpcMkF"));
            if (DateTime.Now.Day != this.mkFolder)
            {
                ConfigSettings.WriteSetting("GpcMkF", DateTime.Now.Day.ToString());
                this.mkFolder = DateTime.Now.Day;
            }
        }

        #region Button Events

        private void btnStartGpc_Click(object sender, EventArgs e)
        {
            if (this.btnStartGpc.Text.ToLower() == "start")
            {
                this.timeWrite.Interval = (Convert.ToInt32(this.txtTimeGpc.Text) * 60) * 0x3e8;
                this.txtTimeGpc.Enabled = false;
                this.CDRDirGPC = this.txtDirGpc.Text;
                this.txtDirGpc.Enabled = false;
                this.ServerFTPGPC = this.txtServerGpc.Text;
                this.txtServerGpc.Enabled = false;
                this.UserFTPGPC = this.txtUserGpc.Text;
                this.txtUserGpc.Enabled = false;
                this.PassFTPGPC = this.txtPassGpc.Text;
                this.txtPassGpc.Enabled = false;
                this.btnStartGpc.Text = "Stop";

                if (this.CDRDirGPC.Substring(this.CDRDirGPC.Length - 1) != @"\")
                    this.CDRDirGPC = this.CDRDirGPC + @"\";

                if (!Directory.Exists(this.CDRDirGPC))
                    Directory.CreateDirectory(this.CDRDirGPC);

                if (!Directory.Exists(this.CDRDirGPC + @"Sent\"))
                    Directory.CreateDirectory(this.CDRDirGPC + @"Sent\");

                if (!Directory.Exists(this.CDRDirGPC + @"NotSent\"))
                    Directory.CreateDirectory(this.CDRDirGPC + @"NotSent\");

                this.WriteCDRGPC();
            }
            else
            {
                this.txtDirGpc.Enabled = true;
                this.txtServerGpc.Enabled = true;
                this.txtUserGpc.Enabled = true;
                this.txtPassGpc.Enabled = true;
                this.btnStartGpc.Text = "Start";
                this.timeWrite.Stop();
            }
        }

        private void btnResendGpc_Click(object sender, EventArgs e)
        {
            string str = DateTime.Now.ToString("yyyyMMdd");
            DirectoryInfo info2 = new DirectoryInfo(this.CDRDirGPC);
            foreach (FileInfo info3 in info2.GetFiles("*.bil"))
            {
                try
                {
                    if (Path.GetFileName(info3.FullName).Length > 12)
                        str = Path.GetFileName(info3.FullName).Substring(3, 8); // Get folder name in file name

                    if (Util.ToInteger(Util.GetAppSettings("GpcMkF")) != DateTime.Now.Day)
                    {
                        ConfigSettings.WriteSetting("GpcMkF", DateTime.Now.Day.ToString());

                        // Make remote folder over FTP
                        this.MakeDir(DateTime.Now.ToString("yyyyMMdd"));
                    }

                    //Upload file
                    bool result = Upload(str, info3.FullName);

                    if (result)
                    {
                        if (!Directory.Exists(this.CDRDirGPC + @"Sent\" + str + @"\"))
                            Directory.CreateDirectory(this.CDRDirGPC + @"Sent\" + str + @"\");

                        info3.MoveTo(this.CDRDirGPC + @"Sent\" + str + @"\" + info3.Name);
                        this.WriteLog("Transfer CDR file " + this.CDRDirGPC + info3.Name + " successfully " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    }
                }
                catch (Exception ex4)
                {
                    this.WriteLog("Transfer CDR error: " + ex4.Message);
                    this.timeWrite.Start();
                    return;
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtLogWriter.Text = "";
            this.txtLogFtp.Text = "";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        #endregion Button Events

        #region Functions

        private void WriteCDRGPC()
        {
            this.timeWrite.Stop();
            
            SqlConnection cnn = new SqlConnection(Util.GetAppSettings("ConnStrGPC"));
            SqlCommand cmd = new SqlCommand("vn1102_GetCDR", cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;
            DataSet dataSet = new DataSet();
            try
            {
                cnn.Open();
                adapter.Fill(dataSet);
            }
            catch (Exception ex)
            {
                this.WriteLog("Cannot get data: " + ex.Message + "\r\n");
                this.timeWrite.Start();
                return;
            }
            finally
            {
                cnn.Close();
            }

            if (dataSet.Tables[0].Rows.Count > 0)
            {
                if (this.SeqNumGpc < 0x270f)
                {
                    this.SeqNumGpc++;
                }
                else
                {
                    this.SeqNumGpc = 0;
                }
                ConfigSettings.WriteSetting("SeqNumGpc", this.SeqNumGpc.ToString());

                string str = DateTime.Now.ToString("yyyyMMdd");
                string fileName = "";
                this.WriteLog("Start writing CDR " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));

                if (!Directory.Exists(this.CDRDirGPC + @"NotSent\" + str))
                    Directory.CreateDirectory(this.CDRDirGPC + @"NotSent\" + str);

                fileName = this.CDRDirGPC + @"NotSent\" + str + @"\dec8x78." + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + this.SeqNumGpc.ToString("0000") + ".txt";
                FileInfo info = new FileInfo(fileName);
                try
                {
                    // Create CDR file
                    using (StreamWriter sw = new StreamWriter(File.Open(fileName, FileMode.CreateNew), System.Text.Encoding.Unicode))
                    {
                        for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
                        {
                            string str2 = dataSet.Tables[0].Rows[i]["ServiceID"].ToString();
                            string str3 = ((((((("M\t" + "84" + str2.Substring(str2.Length - 4) + "\t") + dataSet.Tables[0].Rows[i]["MobileNo"].ToString() + "\t") + Convert.ToDateTime(dataSet.Tables[0].Rows[i]["RequestTime"]).ToString("yyyyMMddHHmmss") + "\t") + "D\t") + Convert.ToDateTime(dataSet.Tables[0].Rows[i]["RequestTime"]).ToString("yyyyMMddHHmmss") + "\t") + "0\t" + "MAPMO.1:1\t") + "0\t" + "MAP.1:1\t") + "1/160\t" + "7";
                            
                            sw.WriteLine(str3);
                        }
                    }

                    this.WriteLog("Finish writing CDR " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                    this.WriteLog("Writing " + dataSet.Tables[0].Rows.Count.ToString() + " record(s) CDR from DB to file " + fileName);

                    // Update CDR Status=1
                    this.UpdateCDRStatus("ConnStrGPC", 1, this.SeqNumGpc.ToString("0000"), "Success");
                }
                catch (Exception ex2)
                {
                    this.SeqNumGpc--;
                    ConfigSettings.WriteSetting("SeqNumGpc", this.SeqNumGpc.ToString());

                    // Update CDR Status=0
                    this.UpdateCDRStatus("ConnStrGPC", 0, "", ex2.ToString().Substring(0, 250));

                    this.WriteLog("Writing CDR error: " + ex2.Message);
                    this.timeWrite.Start();
                    return;
                }
            }
            if (chkEnableTransfer.Checked)
                this.TransferCdr();

            this.timeWrite.Start();
        }

        private void TransferCdr()
        {
            string str = DateTime.Now.ToString("yyyyMMdd");

            DirectoryInfo info2 = new DirectoryInfo(this.CDRDirGPC + @"NotSent\" + str + @"\");
            foreach (FileInfo info3 in info2.GetFiles("*.bil"))
            {
                if (Path.GetFileName(info3.FullName).Length > 12)
                    str = Path.GetFileName(info3.FullName).Substring(3, 8); // Get folder name in file name

                if (this.mkFolder != DateTime.Now.Day)
                {
                    ConfigSettings.WriteSetting("GpcMkF", DateTime.Now.Day.ToString());
                    this.mkFolder = DateTime.Now.Day;

                    // Make remote folder over FTP
                    this.MakeDir(DateTime.Now.ToString("yyyyMMdd"));
                }

                bool result = Upload(str, info3.FullName);

                if (result)
                {
                    if (!Directory.Exists(this.CDRDirGPC + @"Sent\" + str))
                        Directory.CreateDirectory(this.CDRDirGPC + @"Sent\" + str);

                    info3.MoveTo(this.CDRDirGPC + @"Sent\" + str + @"\" + info3.Name);
                    this.WriteLogFTP("Movec file " + info3.Name + " to " + this.CDRDirGPC + @"Sent\" + str + @"\" + " successfully at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
                }
            }
        }

        #region Transfer FTP
        /// <summary>
        /// Method to upload the specified file to the specified FTP Server
        /// </summary>
        /// <param name="filename">file full name to be uploaded</param>
        private bool Upload(string dirname, string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.txtServerGpc.Text.Trim() + "/" + dirname + "/" + fileInf.Name));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(this.txtUserGpc.Text.Trim(), this.txtPassGpc.Text.Trim());

            // By default KeepAlive is true, where the control connection is not closed after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();

                this.WriteLogFTP("Transfer file " + fileInf.Name + " successful at " + DateTime.Now);

                return true;
            }
            catch (Exception ex)
            {
                this.WriteLogFTP(string.Format("Upload failed: {0}", ex.Message));
                return false;
            }
        }

        private void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + this.txtServerGpc.Text.Trim() + "/" + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(this.txtUserGpc.Text.Trim(), this.txtPassGpc.Text.Trim());
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();

                this.WriteLogFTP(string.Format("Folder named {0} has created.", dirName));
            }
            catch
            {
                this.WriteLogFTP("Make ftp folder failed, may already!");
            }
        }
        #endregion Transfer FTP

        #region Write Log
        private void WriteLog(string s)
        {
            lock (this.txtLogWriter)
            {
                if ((this.txtLogWriter.TextLength + s.Length) > (int)0x8000)
                {
                    this.txtLogWriter.Clear();
                }
                this.txtLogWriter.Text = this.txtLogWriter.Text + s + "\r\n";
                this.txtLogWriter.ScrollToCaret();
            }
        }

        private void WriteLogFTP(string s)
        {
            lock (this.txtLogFtp)
            {
                if ((this.txtLogFtp.TextLength + s.Length) > (int)0x8000)
                {
                    this.txtLogFtp.Clear();
                }
                this.txtLogFtp.Text = this.txtLogFtp.Text + s + "\r\n";
                this.txtLogFtp.ScrollToCaret();
            }
        }
        #endregion Write Log

        #region Functions
        private void UpdateCDRStatus(string cnnStr, byte statusCdr, string CdrIndex, string exStr)
        {
            SqlConnection cnn = new SqlConnection(Util.GetAppSettings(cnnStr));
            SqlCommand cmd = new SqlCommand("vn1102_Update_CDR_Status", cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@CDRStatus", SqlDbType.TinyInt).Value = statusCdr;
            cmd.Parameters.Add("@CDRIndex", SqlDbType.VarChar).Value = CdrIndex;
            cmd.Parameters.Add("@ExceptionString", SqlDbType.VarChar).Value = exStr;

            try
            {
                cnn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                this.WriteLog("Cannot execute SP: " + ex.Message + "\r\n");
                return;
            }
            finally
            {
                cnn.Close();
            }
        }

        public static string RemoveSpecialChar(string unicodeString)
        {
            try
            {
                // Remove VietNamese character
                unicodeString = unicodeString.ToLower();
                unicodeString = Regex.Replace(unicodeString, "[áàảãạâấầẩẫậăắằẳẵặ]", "a");
                unicodeString = Regex.Replace(unicodeString, "[éèẻẽẹêếềểễệ]", "e");
                unicodeString = Regex.Replace(unicodeString, "[iíìỉĩị]", "i");
                unicodeString = Regex.Replace(unicodeString, "[óòỏõọơớờởỡợôốồổỗộ]", "o");
                unicodeString = Regex.Replace(unicodeString, "[úùủũụưứừửữự]", "u");
                unicodeString = Regex.Replace(unicodeString, "[yýỳỷỹỵ]", "y");
                unicodeString = Regex.Replace(unicodeString, "[đ]", "d");

                // Remove space
                unicodeString = unicodeString.Replace(" ", "");

                // Remove special character
                //unicodeString = Regex.Replace(unicodeString, "[`-=+:;'?/><,.]", "");
                unicodeString = Regex.Replace(unicodeString, "[`!-+=?/>.<,{}[]|]\\]", "");

                return unicodeString;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion Functions

        #endregion Functions

        #region Timer Events

        private void timeFTP_Tick(object sender, EventArgs e)
        {
            
        }

        private void timeWrite_Tick(object sender, EventArgs e)
        {
            this.WriteCDRGPC();
        }

        #endregion Timer Events

    }
}